<!DOCTYPE html><html><head><title>Sencha Documentation Project</title><script type="text/javascript" src="../ext-all.js"></script><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../scrollbars.css" type="text/css"><link rel="stylesheet" href="../docs.css" type="text/css"><link id="styleCss" rel="stylesheet" href="../style.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script><link rel="stylesheet" href="../prettify.css" type="text/css"><!-- link(rel: 'stylesheet', href: req.baseURL + '/css/ext4.css', type: 'text/css')--><link rel="shortcut icon" type="image/ico" href="../favicon.ico"><!--[if IE]>
<style type="text/css">.head-band { display: none; }
.header { border: 0; top: 0; left: 0px; background: url(../header.gif) repeat-x; }
.doc-tab .members .member a.more { background-color: #efefef; }
</style><link rel="stylesheet" href="/new/css/ie.css" type="text/css"><![endif]-->
</head><body id="ext-body" class="iScroll"><div id="notice" class="notice">For up to date documentation and features, visit 
<a href="http://docs.sencha.com/ext-js/4-0">http://docs.sencha.com/ext-js/4-0</a></div><div class="wrapper"><div class="head-band"></div><div class="header"><h2><a href="../index.html">Sencha Documentation</a></h2></div><div id="search"><form><input type="text" placeholder="Search" id="search-field" autocomplete="off" name="q"></form><div id="search-box"></div></div><div id="treePanel"></div><div id="container"><script type="text/javascript">

    req = {
        liveURL: '.',
        standAloneMode: true,
        origDocClass: 'undefined',
        docClass: 'undefined',
        docReq: 'undefined',
        version: '4.0',
        baseURL: '.',
        baseDocURL: '.',
        baseProdURL: '.'
    };

    clsInfo = {};



</script>

<script type="text/javascript" src="../search.js"></script>
<!--script type="text/javascript" src="/new/javascripts/app/examples.js"></script-->
<script type="text/javascript" src="../class_tree.js"></script>
<script type="text/javascript" src="../class_doc.js"></script>
<div id="top-block" class="top-block"></div><div id="docContent"><div class="guide"><h1>Ext JS 4 Class System</h1>

<hr></hr>

<p>For the first time in its history, Ext JS went through a huge refactoring from the ground up with the new class system. The new architecture stands behind almost every single class written in Ext JS 4.x, hence it's important to understand it well before you start coding.</p>

<p>This manual is intended for any developer who wants to create new or extend existing classes in Ext JS 4.x. It's divided into 3 main sections:</p>

<ul><li>Section I: <a href="class_system.html#">"Overview"</a> explains the need for a robust class system</li><li>Section II: <a href="class_system.html#">"Hands-on"</a> provides detailed step-by-step code examples</li><li>Section III: <a href="class_system.html#">"Errors Handling & Debugging"</a> gives useful tips & tricks on how to deal with exceptions</li><li>Section III: <a href="class_system.html#">"Under the Hood"</a> discusses about technical concept and implementation</li></ul>

<p>All code examples used in this manual can be downloaded <a href="class_system.html#download">here</a></p>

<h2>I. Overview</h2>

<hr></hr>

<p>Ext JS 4 ships with more than 300 classes. We have a huge community of more than 200,000 developers to date, coming from various programming backgrounds all over the world. At that scale of a framework, we face a big challange of providing a common code architecture that is:</p>

<ul><li>familiar and simple to learn</li><li>fast to develop, easy to debug, painless to deploy</li><li>well-organized, extensible and maintainable</li></ul>

<p>JavaScript is a classless, <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-oriented</a> language. Hence by nature, one of the language's most powerful features is flexibility. It can get the same job done by many different ways, in many different coding styles and techniques. That feature, however, comes with the cost of unpredictability. Without a unified structure, JavaScript code can be really hard to understand, maintain and re-use.</p>

<p><a href="http://en.wikipedia.org/wiki/Class-based_programming">Class-based</a> programming, on the other hand, still stays as the most popular model of OOP. <a href="http://en.wikipedia.org/wiki/Category:Class-based_programming_languages">Class-based languages</a> usually require strong-typing, provide encapsulation, and come with standard coding convention. By generally making developers adhere to a large set of principle, written code is more likely to be predictable, extensible and scalable over time. However, they don't have the same dynamic capability found in such language as JavaScript.</p>

<p>Each approach has its own pros and cons, but can we have the good parts of both at the same time while concealing the bad parts? The answer is yes, and we've implemented the solution in Ext JS 4.</p>

<h2>II. Naming Convention</h2>

<h3>1) Classes</h3>

<ul><li><p>Class names may only contain <strong>alphanumeric</strong> characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character. For example:</p><ul><li><code>MyCompany.useful_util.Debug_Toolbar</code> is discouraged</li><li><p><code>MyCompany.util.Base64</code> is acceptable</p></li></ul></li><li><p>Class names should be grouped into packages where appropriate and properly namespaced using object property dot-notation (.). At the minimum, there should be one unique top-level namespace followed by the class name. For example:</p><ul><li><code>MyCompany.data.CoolProxy</code></li><li><p><code>MyCompany.Application</code></p></li></ul></li><li><p>The top-level namespaces and the actual class names should be in CamelCased, everything else should be all lower-cased. For example:</p><ul><li><p><code>MyCompany.form.action.AutoLoad</code></p></li></ul></li><li><p>Classes that are not distributed by Sencha should never use <code>Ext</code> as the top-level namespace.</p></li><li><p>Acronyms should also follow CamelCased convention listed above. For example:</p><ul><li><code>Ext.data.JsonProxy</code> instead of <code>Ext.data.JSONProxy</code></li><li><code>MyCompany.util.HtmlParser</code> instead of <code>MyCompary.parser.HTMLParser</code></li><li><code>MyCompany.server.Http</code> instead of <code>MyCompany.server.HTTP</code></li></ul></li></ul>

<h3>2) Source Files</h3>

<ul><li><p>The names of the classes map directly to the file paths in which they are stored. As a result, there must only be one class per file. For example:</p><ul><li><code>Ext.util.Observable</code> is stored in <code>path/to/src/Ext/util/Observable.js</code></li><li><code>Ext.form.action.Submit</code> is stored in <code>path/to/src/Ext/form/action/Submit.js</code></li><li><p><code>MyCompany.chart.axis.Numeric</code> is stored in <code>path/to/src/MyCompany/chart/axis/Numeric.js</code></p><p>whereby <code>path/to/src</code> is the directory of your application's classes. All classes should stay inside one directory and should be properly namespaced for the best development, maintenance and deployment experience.</p></li></ul></li></ul>

<h3>3) Methods and Variables</h3>

<ul><li><p>Similarly to class names, method and variable names may only contain <strong>alphanumeric</strong> characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character.</p></li><li><p>Method and variable names should always be in camelCased. This also applies to acronyms.</p></li><li><p>Examples</p><ul><li>Acceptable method names:<ul><li><code>encodeUsingMd5()</code></li><li><code>getHtml()</code> instead of <code>getHTML()</code></li><li><code>getJsonResponse()</code> instead of <code>getJSONResponse()</code></li><li><code>parseXmlContent()</code> instead of <code>parseXMLContent()</code></li></ul></li><li>Acceptable variable names:<ul><li><code>var isGoodName</code></li><li><code>var base64Encoder</code></li><li><code>var xmlReader</code></li><li><code>var httpServer</code></li></ul></li></ul></li></ul>

<h3>4) Properties</h3>

<ul><li><p>Class property names follow the exact same convention with methods and variables mentioned above, except the case when they are static constants.</p></li><li><p>Static class properties that are constants should be all upper-cased. For example:</p><ul><li><code>Ext.MessageBox.YES = "Yes"</code></li><li><code>Ext.MessageBox.NO  = "No"</code></li><li><code>MyCompany.alien.Math.PI = "4.13"</code></li></ul></li></ul>

<h2>II. Hands-on</h2>

<hr></hr>

<h3>1. Declaration</h3>

<h4>1.1) The Old Way</h4>

<p>If you have ever used any previous version of Ext JS, you are certainly familiar with <code>Ext.extend</code> to create a class:</p>

<pre class="prettyprint"><code>var MyWindow = Ext.extend(Object, { ... });</code></pre>

<p>This approach is easy to followed to create a new class that inherit from another. Other than direct inheritance, however, we didn't have a fluent API for other aspects of class creation, such as configuration, statics and mixins. We will be reviewing these items in details shortly.</p>

<p>Let's take a look at another example:</p>

<pre class="prettyprint"><code>My.cool.Window = Ext.extend(Ext.Window, { ... });</code></pre>

<p>In this example we want to <a href="http://en.wikipedia.org/wiki/Namespace_(computer_science)">namespace</a> our new class, and make it extend from <code>Ext.Window</code>. There are two concerns we need to address:</p>

<ol><li><code>My.cool</code> needs to be an existing object before we can assign <code>Window</code> as its property</li><li><code>Ext.Window</code> needs to exist / loaded on the page before it can be referenced</li></ol>

<p>The first item is usually solved with <code>Ext.namespace</code> (aliased by <code>Ext.ns</code>). This method recursively transverse through the object / property tree and create them if they don't exist yet. The  boring part is you need to remember adding them above <code>Ext.extend</code> all the time.</p>

<pre class="prettyprint"><code>Ext.ns('My.cool');
My.cool.Window = Ext.extend(Ext.Window, { ... });</code></pre>

<p>The second issue, however, is not easy to address because <code>Ext.Window</code> might depend on many other classes that it directly / indirectly inherits from, and in turn, these dependencies might depend on other classes to exist. For that reason, applications written before Ext JS 4 usually include the whole library in the form of <code>ext-all.js</code> even though they might only need a small portion of the framework.</p>

<h3>1.2) The New Way</h3>

<p>Ext JS 4 eliminates all those drawbacks with just one single method you need to remember for class creation: <code>Ext.define</code>. Basic syntax:</p>

<pre class="prettyprint"><code>Ext.define({String} className, {Object} members, {Function} onClassCreated);</code></pre>

<ul><li><code>className</code>: The <a href="class_system.html#">class name</a></li><li><code>members</code> is an object represents a collection of class members in key-value pairs</li><li><code>onClassCreated</code> is an optional function callback to be invoked when all dependencies of this class are ready, and the class itself is fully created. Due to the <a href="class_system.html#">new asynchronous nature</a> of class creation, this callback can be useful in many situations. These will be discussed further in <a href="class_system.html#">Section IV</a></li></ul>

<p><strong>Example:</strong></p>

<pre class="prettyprint"><code>Ext.define('My.sample.Person', {
    name: 'Unknown',

    constructor: function(name) {
        if (name) {
            this.name = name;
        }

        return this;
    },

    eat: function(foodType) {
        alert(this.name + " is eating: " + foodType);

        return this;
    }
});

var aaron = new My.sample.Person("Aaron");
    aaron.eat("Salad"); // alert("Aaron is eating: Salad");</code></pre>

<h3>2. Configuration</h3>

<h4>2.1) The Old Way</h4>

<p>Previous to version 4, we didn't really have a way to distinguish between class properties and user-supplied configurations. Configurations were defined as normal class properties and documented using <code>@cfg</code> annotation. Let's take a look at a sample class. It's rather lengthy but it well describes the problems as a whole:</p>

<pre class="prettyprint"><code>Ext.ns('My.sample');
My.own.Window = Ext.extend(Object, {
   /** @readonly */
    isWindow: true,

   /** @cfg {String} title The default window's title */
    title: 'Title Here',

   /** @cfg {Object} bottomBar The default config for the bottom bar */
    bottomBar: {
        enabled: true,
        height: 50,
        resizable: false
    },

    constructor: function(config) {
        Ext.apply(this, config || {});

        this.setTitle(this.title);
        this.setBottomBar(this.bottomBar);

        return this;
    },

    setTitle: function(title) {
        // Change title only if it's a non-empty string
        if (!Ext.isString(title) || title.length === 0) {
            alert('Error: Title must be a valid non-empty string');
        }
        else {
            this.title = title;
        }

        return this;
    },

    getTitle: function() {
        return this.title;
    },

    setBottomBar: function(bottomBar) {
        // Create a new instance of My.own.WindowBottomBar if it doesn't exist
        // Change the config of the existing instance otherwise
        if (bottomBar && bottomBar.enabled) {
            if (!this.bottomBar) {
                this.bottomBar = new My.own.WindowBottomBar(bottomBar);
            }
            else {
                this.bottomBar.setConfig(bottomBar);
            }
        }

        return this;
    },

    getBottomBar: function() {
        return this.bottomBar;
    }
});</code></pre>

<p>In short, <code>My.own.Window</code>:</p>

<ul><li>accepts a config object during instantiation, then merge with the default properties of the class</li><li>allows <code>title</code> and <code>bottomBar</code> to be changed during run-time via setters</li></ul>

<p>This approach has one advantage, yet it's the one drawback at the same time: you can overwrite any members of this class' instances during instantiation, including private methods and properties that should never be overwritten. The trade-off of encapsutation for flexibilty caused misusage in many applications in the past, which led to poor design as well as bad debugging and maintenance experience.</p>

<p>Further more, there are other limitations:</p>

<ul><li><p><code>Ext.apply</code> doesn't merge object properties recursively. So in this example, you can't just override <code>bottomBar.height</code> to <code>60</code>, for instance, without supplying other default properties of <code>bottomBar</code> as well.</p></li><li><p>Getters and setters have to be manually defined for each and every config property. It's not programmatically possible to clearly tell what properties are configurations, hence setters and getters can't be automatically generated.</p></li></ul>

<h4>2.2) The New Way</h4>

<p>In Ext JS 4, we introduce a dedicated <code>config</code> property that gets processed by the powerful <a href="class_system.html#">Ext.Class pre-processors</a> before the class is created. Let's rewrite the above example:</p>

<pre class="prettyprint"><code>Ext.define('My.own.Window', {
   /** @readonly */
    isWindow: true,

    config: {
        title: 'Title Here',

        bottomBar: {
            enabled: true,
            height: 50,
            resizable: false
        }
    },

    constructor: function(config) {
        this.initConfig(config);

        return this;
    },

    applyTitle: function(title) {
        if (!Ext.isString(title) || title.length === 0) {
            alert('Error: Title must be a valid non-empty string');
        }
        else {
            return title;
        }
    },

    applyBottomBar: function(bottomBar) {
        if (bottomBar && bottomBar.enabled) {
            if (!this.bottomBar) {
                return new My.own.WindowBottomBar(bottomBar);
            }
            else {
                this.bottomBar.setConfig(bottomBar);
            }
        }
    }
});</code></pre>

<p>And here's an example of how it can be used:</p>

<pre class="prettyprint"><code>var myWindow = new My.own.Window({
    title: 'Hello World',
    bottomBar: {
        height: 60
    }
});

alert(myWindow.getTitle()); // alerts "Hello World"

myWindow.setTitle('Something New');

alert(myWindow.getTitle()); // alerts "Something New"

myWindow.setTitle(null); // alerts "Error: Title must be a valid non-empty string"

myWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100</code></pre>

<p>With these changes:</p>

<ul><li><code>My.own.Window</code> class' code is significantly reduced, with even more functionalities</li><li>Configurations are completely encapsulated from other class members</li><li>Setters and getters, together with <a href="class_system.html#">`apply*`</a> and <a href="class_system.html#">`reset*`</a> methods for every config property are automatically generated into the class' prototype during class creation, if the class does not have these methods already defined.</li></ul>

<h4>2.3) `apply*`</h4>

<h3>3. Statics</h3>

<h3>4. Inheritance</h3>

<h3>5. Mixins</h3>

<h3>6. Dependencies</h3>

<h2>III. Errors Handling & Debugging</h2>

<hr></hr>

<h2>IV. Under the Hood</h2>

<hr></hr>

<h3>1. Ext.Base</h3>

<h3>2. Ext.Class and Pre-processors</h3>

<h3>3. Ext.ClassManager and Post-processors</h3>

<h3>4. Ext.Loader</h3>

<h2>See Also</h2>

<ul><li><a href="http://www.sencha.com/blog/countdown-to-ext-js-4-dynamic-loading-and-new-class-system">Dynamic Loading and the New Class System</a></li><li><a href="http://edspencer.net/2011/01/classes-in-ext-js-4-under-the-hood.html">Classes in Ext JS 4: Under the Hood</a></li><li><a href="http://edspencer.net/2011/01/ext-js-4-the-class-definition-pipeline.html">The Class Defition Pipeline</a></li></ul>

<h2>This guide is a work in progress.</h2>

<p>Please check back soon</p></div></div></div></div></body></html>